﻿using BestTrader.Cms.Core.Helper;
using BestTrader.Cms.Core.Options;
using BestTrader.Cms.IServices;
using BestTrader.Cms.ViewModels;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace BestTrader.Cms.Services
{
    /// <summary>
    /// [.NET Core 中正确使用 HttpClient 的姿势](https://www.cnblogs.com/willick/p/net-core-httpclient.html)
    /// </summary>
    public class YunPayClientService
    {
        protected YunpayOption _payOption;
        protected ILogger<YunPayClientService> _logger;
        public HttpClient Client { get; private set; }

        public YunPayClientService(IOptionsSnapshot<YunpayOption> options, HttpClient httpClient, ILogger<YunPayClientService> logger)
        {
            _payOption = options.Get("YUNPAY");
            httpClient.BaseAddress = new Uri(_payOption.BaseUrl);
            //httpClient.DefaultRequestHeaders.Add("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            //httpClient.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
            Client = httpClient;
            _logger = logger;
        }

        /// <summary>
        /// 1、 二维码调用到本地服务器显示
        /// </summary>
        /// <param name="orderNo"></param>
        /// <param name="amount"></param>
        /// <param name="ip4"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public async Task<string> GetYunPayData(string orderNo, decimal amount, string ip4, string type = "1")
        {
            var url = _payOption.BaseUrl;
            var data = orderNo; // DateTime.Now.ToString("yyyyMMddHHmmss");
            var money = amount.ToString(); //"1.00";
            var token = GetYunPayToken(money, ip4, data, type);

            List<KeyValuePair<String, String>> paramList = new List<KeyValuePair<String, String>>();
            paramList.Add(new KeyValuePair<string, string>("appid", _payOption.AppId));
            paramList.Add(new KeyValuePair<string, string>("data", data));
            paramList.Add(new KeyValuePair<string, string>("money", money));
            paramList.Add(new KeyValuePair<string, string>("type", type));
            paramList.Add(new KeyValuePair<string, string>("token", token));
            paramList.Add(new KeyValuePair<string, string>("uip", ip4));
            paramList.Add(new KeyValuePair<string, string>("appkey", _payOption.AppKey));
            //var response = Client.PostAsync(new Uri(url), new FormUrlEncodedContent(paramList)).Result;
            //String result = response.Content.ReadAsStringAsync().Result;
            //{ "state":"1","qrcode":"HTTPS:\/\/QR.ALIPAY.COM\/tsx039507ncfffzkpbjqe68","order":"3b9933c680178c1aa9513b61e35483db","data":"20190227133527","money":"1.00","times":"1551246091","orderstatus":"0","text":"10088"}
            var response = await Client.PostAsync(new Uri(url), new FormUrlEncodedContent(paramList));
            return await response.Content.ReadAsStringAsync();
        }

        string GetYunPayToken(string money, string ip4, string data, string type)
        {
            var str = $"appid={_payOption.AppId}&data={data}&money={money}&type={type}&uip={ip4}&appkey={_payOption.AppKey}";
            var result = MD5EncryptHelper.Get32MD5Two(str).ToLower();
            return result;
        }

        string GetOrderToken(string ip4, string type)
        {
            var str = $"appid={_payOption.AppId}&type={type}&uip={ip4}&appkey={_payOption.AppKey}";
            var result = MD5EncryptHelper.Get32MD5Two(str).ToLower();
            return result;
        }

        /// <summary>
        /// 2、订单状态 查询
        /// </summary>
        /// <param name="orderNo">第三方返回的订单号</param>
        /// <param name="ip4"></param>
        /// <returns></returns>
        public async Task<string> GetYunPayOrder(string orderNo, string ip4, string type = "1") {
            var url = $"{_payOption.BaseUrl}order";
            var token = GetOrderToken(ip4, type);

            List<KeyValuePair<String, String>> paramList = new List<KeyValuePair<String, String>>();
            paramList.Add(new KeyValuePair<string, string>("appid", _payOption.AppId));
            paramList.Add(new KeyValuePair<string, string>("order", orderNo));
            paramList.Add(new KeyValuePair<string, string>("type", type));
            paramList.Add(new KeyValuePair<string, string>("uip", ip4));
            paramList.Add(new KeyValuePair<string, string>("token", token));
            var response = await Client.PostAsync(new Uri(url), new FormUrlEncodedContent(paramList));
            return await response.Content.ReadAsStringAsync();
        }
    }
}
